package cn.com.huzo.web.util;

import java.util.Collection;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Session工具类
 * <p>
 * @author 吴旭
 */
public class ShiroSessionHelper {

    @Autowired
    private SessionDAO sessionDAO;

    public ShiroSessionHelper() {
    }

    /**
     * 根据用户名得到session
     * <p>
     * @param username 用户名
     * @return
     */
    public Session getSessionByUsername(String username) {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            if (null != session && StringUtils.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)), username)) {
                return session;
            }
        }
        return null;
    }

    /** 踢除用户
     * <p>
     * @param username
     */
    public void kickOutUser(String username) {
        Session session = getSessionByUsername(username);
        if (null != session) {
            //ShiroAuthorizationHelper.clearAuthenticationInfo(session.getId());
            session.setTimeout(0L);
        }
    }
}
